import type { App } from 'vue'
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import { goodsRoutes } from './modules/goods'
import { orderRoutes } from './modules/order'
import { storeRoutes } from './modules/store'
import { courseRoutes } from './modules/course'
import { classroomRoutes } from './modules/classroom'
import { groundRoutes } from './modules/ground'
// 订单核销
import { writeoffRoutes } from './modules/writeoff'
import { financeRoutes } from './modules/finance'

export const Layout = () => import('@/layout/index.vue')

// 静态路由
export const constantRoutes: RouteRecordRaw[] = [
  {
    path: '/redirect',
    component: Layout,
    meta: { hidden: true },
    children: [
      {
        path: '/redirect/:path(.*)',
        component: () => import('@/views/redirect/index.vue'),
      },
    ],
  },

  {
    path: '/login',
    component: () => import('@/views/login/index.vue'),
    meta: { hidden: true },
  },

  {
    path: '/',
    name: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        component: () => import('@/views/dashboard/index.vue'),
        // 用于 keep-alive 功能，需要与 SFC 中自动推导或显式声明的组件名称一致
        // 参考文档: https://cn.vuejs.org/guide/built-ins/keep-alive.html#include-exclude
        name: 'Dashboard',
        meta: {
          title: '工作台',
          icon: 'homepage',
          affix: true,
          keepAlive: true,
        },
      },
    ],
  },

  // ...goodsRoutes, // 商品管理
  // ...orderRoutes, // 订单管理
  ...writeoffRoutes, // 订单核销
  ...classroomRoutes, // 教室租赁
  ...groundRoutes, // 场地预订
  ...courseRoutes,  // 课程商品
  ...financeRoutes, // 财务中心
  ...storeRoutes, // 门店管理

  {
    path: '/401',
    component: () => import('@/views/error-page/401.vue'),
    meta: { hidden: true },
  },
  // 404 page must be placed at the end !!!
  {
    path: '/:pathMatch(.*)',
    component: () => import('@/views/error-page/404.vue'),
    meta: { title: '404', hidden: true },
  },
]

/**
 * 创建路由
 */
const router = createRouter({
  history: createWebHashHistory(),
  routes: constantRoutes,
  // 刷新时，滚动条位置还原
  scrollBehavior: () => ({ left: 0, top: 0 }),
  sensitive: true, // 匹配路由时严格区分大小写
})

// 全局注册 router
export function setupRouter(app: App<Element>) {
  app.use(router)
}

/**
 * 重置路由
 */
export function resetRouter() {
  router.replace({ path: '/login' })
}

export default router
